<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Redis;
use DB;
class Goods extends Model
{
  
	/**
     * 关联到模型的数据表
     *
     * @var string
     */

	protected $table = 'goods';
    


	//指定填充字段 create使用
	protected $fillable = [
		'number','goods_name','shop_price','goods_price','shop_id','goods_detail','cat_id','pic'	
	];


    //指定模型是否有时间戳
	public $timestamps = false;

	/**
     * 获取商品详情缓存
     *	商品信息存在redis缓存取其中的数据 如果不存在取数据库再存入缓存
     * @var level
     */

	public function getGoods($id)
	{	
		//redis键
		$key = 'good'.$id;
        if(Redis::exists($key)){          
            $goods = Redis::get($key);
        }else{
            $goods = self::join('goods_info','goods_info.goods_id','=','goods.goods_id')
                            ->where('goods.goods_id',$id)
                            ->select('goods.*','goods_info.*')
                            ->get();
            $goods = json_encode($goods); 
            Redis::set($key,$goods); 
            Redis::expire($key, 600000);
        }
       $goods = json_decode($goods);
       //处理尺寸
       $goods[0]->size = explode(",", $goods[0]->size);
       //处理颜色
       $goods[0]->color = explode(",", $goods[0]->color);
       return $goods;
	}

	/**
     * 详细图片redis缓存
     *	前三张缩略 后面详情
     * @var $id
     */
	public function getImgs($id){
		$key = 'good_img'.$id;
		if(Redis::exists($key)){          
            $goodsimgs = Redis::get($key);
        }else{
			$goodsimgs = DB::table('goods_imgs')->where('goods_id',$id)->skip(3)->take(8)->get();
			$goodsimgs = json_encode($goodsimgs);
			Redis::set($key,$goodsimgs); 
			Redis::expire($key, 600000);
		}
		$goodsimgs = json_decode($goodsimgs);
		$imgs = [];
        foreach ($goodsimgs as  $v) {
            $imgs[] = $v->url;
        } 
        return $imgs;
	}

	/**
     * 放大镜图片
     *	
     * @var $id
     */
	public function getImg($id){
		$goodsimg = DB::table('goods_imgs')->where('goods_id',$id)->take(3)->get();
		$img = [];
        foreach ($goodsimg as  $v) {
            $img[] = $v->url;
        } 
        return $img;
	}

	/**
     * 商品评论
     *	
     * @var $id
     */

	public function getAssess($id){
		$assess = DB::table('goods_assess')
            ->join('users', 'users.id', '=', 'goods_assess.uid')
            ->where('goods_id',$id)
            ->paginate(8);
        return $assess;
	}

	/**
     * 商品评论数
     *	
     * @var $id
     */
	public function getCount($id){
		$count = [];
		$count[0] = DB::table('goods_assess')->where('goods_id',$id)->count();//全部
        $count[1] = DB::table('goods_assess')->where('level',0)->where('goods_id',$id)->count();//好评
        $count[2] = DB::table('goods_assess')->where('level',1)->where('goods_id',$id)->count();//中评
        $count[3] = DB::table('goods_assess')->where('level',2)->where('goods_id',$id)->count();//差评
        return $count;
	}
}


